public with sharing class ScheduledCargoController {

	public String scid {get;private set;}
	public ScheduledCargo__c sc ;
	public Boolean isErr {get;set;}//
	public String  msg {get;set;} 
	public String resJson {get;set;}
	public Boolean isSuccess {get;set;}//

	public String  	pname ;
    public String 	pbrand ;
    public String 	pspec ;
    public String 	pnccode ;
    public String 	pserialNo ;
    public String 	pcategory0 ;
    public String 	pcategory1 ;
    public String searchJson {get;set;}
    public String saveJson {get;set;}

    public ScheduledCargoController() {
        scid = System.currentPageReference().getParameters().get('id');
		sc = [select Id ,OwnerCompany__c,Customer__r.AccountNumber,Status__c,IsSycToNc__c  from ScheduledCargo__c where Id =:scid ];
		if(sc == null)setErr('页面打开错误!');
		if(sc != null && sc.Status__c == '申请中' || sc.Status__c == '已批准' )setErr('审批中或已审批不能修改!');
    }

    
   public void setErr(String message){
      isErr = true;
      ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }
    public void save(){

      	msg = '';
      	if(sc.IsSycToNc__c == true){
        	msg = '已同步NC ,不能修改!';

    		return;
    	}

	      List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
	      if(resList.size() == 0){
	        msg = '保存失败,没有数据!';
	        return;
	      }
	    List<SameBatchNumber__c>   tList = new List<SameBatchNumber__c>();
	    for (Object res : resList) {
	        Map<String ,Object> o = (Map<String ,Object> )res;
	        SameBatchNumber__c sbn = new SameBatchNumber__c();
	        sbn.CargoDetail__c = scid;
	        if(o.get('prodid') == null){
	        	 msg = '产品数据异常!';
	        	return;
	        }
	        sbn.Inventory__c = String.valueOf(o.get('prodid'));

	        sbn.SendYear__c = String.valueOf(o.get('year'));

	        sbn.SendMount1__c = getDecimalValue(o.get('a1'));
	        sbn.SendMount2__c = getDecimalValue(o.get('a2'));
	        sbn.SendMount3__c = getDecimalValue(o.get('a3'));
	        sbn.SendMount4__c = getDecimalValue(o.get('a4'));
	        sbn.SendMount5__c = getDecimalValue(o.get('a5'));
	        sbn.SendMount6__c = getDecimalValue(o.get('a6'));
	        sbn.SendMount7__c = getDecimalValue(o.get('a7'));
	        sbn.SendMount8__c = getDecimalValue(o.get('a8'));
	        sbn.SendMount9__c = getDecimalValue(o.get('a9'));
	        sbn.SendMount10__c = getDecimalValue(o.get('a10'));
	        sbn.SendMount11__c = getDecimalValue(o.get('a11'));
	        sbn.SendMount12__c = getDecimalValue(o.get('a12'));
            sbn.SalesVolume1__c = getDecimalValue(o.get('lm1sale'));
            sbn.SalesVolume2__c = getDecimalValue(o.get('lm2sale'));
            sbn.SalesVolume3__c = getDecimalValue(o.get('lm3sale'));

	        sbn.ExpirationDate__c = o.get('invaliddate') == null ? null :  Date.valueOf(String.valueOf(o.get('invaliddate')).trim());
	    
	        sbn.BatchNumber__c = String.valueOf(o.get('batchcode'));
	        sbn.OtherRequirements__c    = String.valueOf(o.get('remark'));
	        tList.add(sbn);
	    }
	    SavePoint sp = Database.setSavepoint();
	    try {

	    	List<SameBatchNumber__c> dList = [select Id from SameBatchNumber__c where CargoDetail__c =:scid];
	    	if(dList != null && dList.size() > 0) delete dList;
	    	insert tList;
	    	msg = '保存成功!';
	        isSuccess = true;
	    }catch (Exception e) {
	       Database.rollback(sp);
	       msg = '保存失败! '+e.getMessage(); 

	    }	    

	}
	private Decimal getDecimalValue(Object val){
        if(val == null)return null;
        String  d = String.valueOf(val).trim();
        if(d.length() == 0)return null;
        return Decimal.valueOf(d);
    }
      
    public void getOldProductList (){
     	List<Product__c>pList = new List<Product__c>();
    	Set<String>  pids= new Set<String>();
    	List<SameBatchBean> tmp = new List<SameBatchBean>();

    	for(SObject sbn :[select Inventory__c 
    		  from SameBatchNumber__c where CargoDetail__r.Customer__c =:sc.Customer__c  group by Inventory__c ]){
    			pids.add(String.valueOf(sbn.get('Inventory__c')));
    	}
    	if(pids.size() == 0){
    		resJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');
    	 	return;
    	}

    	String sql = 'select Id,Name ,ProductName__c,brand__c,Spec__c ,SerialNo__c ,Model__c ,NCCode__c,Category1__c,Category2__c,Category0__c,zl__c,SealCompany__c ,TypeName__c';
    	 sql += ' from Product__c where  RecordType.DeveloperName = \'NCProduct\' and NCCode__c != null  ';
    	 sql += ' and Id in '+transStr(pids);

        if(String.isBlank(pname) == false ) sql += ' and ProductName__c like \'%'+pname+'%\' ';
    	 if(String.isBlank(pbrand) == false ) sql += '  and Brand__c like \'%'+pbrand+'%\' ';
    	 if(String.isBlank(pspec) == false ) sql += '  and Spec__c like \'%'+pspec+'%\' ';
    	 if(String.isBlank(pnccode) == false ) sql += '  and NCCode__c like \'%'+pnccode+'%\' ';
    	 if(String.isBlank(pcategory0) == false ) sql += '  and Category0__c like \'%'+pcategory0+'%\' ';
    	 if(String.isBlank(pcategory1) == false ) sql += '  and Category1__c like \'%'+pcategory1+'%\' ';
    	 if(String.isBlank(pserialNo) == false ) sql += '  and SerialNo__c like \'%'+pserialNo+'%\' ';

    	pList = Database.query(sql);

    	   	
    	if(pList == null || pList.size() == 0){
 	    	resJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
    	 	return;
    	 }
  
    	Map<String,List<Object>> pMap = getSalesMount(pids);
    	List<SameBatchBean> sbTmp = new List<SameBatchBean>();
    	for (Product__c sbn  : pList) {
    		sbTmp.add(new SameBatchBean(sbn , pMap.get(sbn.NCCode__c)));
    	}
    	
    	resJson = EncodingUtil.urlEncode(JSON.serialize(sbTmp),'UTF-8');

    }
    public  void getDetails(){
    	Map<String,SameBatchNumber__c> tmp = new Map<String,SameBatchNumber__c>();
    	
    	String sql = 'select Id,Inventory__c,Inventory__r.ProductName__c,Inventory__r.Brand__c,Inventory__r.NCCode__c,BatchNumber__c,Inventory__r.Name,'
    	+'OtherRequirements__c ,'
    	+'Name ,CargoDetail__r.Customer__r.Name,Inventory__r.Unit__c,Inventory__r.Model__c,Inventory__r.SerialNo__c,Inventory__r.Spec__c, '
    	+'SendMount1__c,SendMount2__c,SendMount3__c,SendMount4__c,SendMount5__c,SendMount6__c,SendMount7__c,SendMount8__c,'
    	+'SendMount9__c,SendMount10__c,SendMount11__c,SendMount12__c,SendYear__c ,CargoDetail__r.Customer__c,ExpirationDate__c,CargoDetail__r.Name  '
    	+'from SameBatchNumber__c';
    	
    	sql += ' where CargoDetail__c =\''+scid+'\' Order by Inventory__c '; 
    	List<SameBatchNumber__c> snList = Database.query(sql);
    	Set<String> pcodes = new Set<String> ();
    	for (SameBatchNumber__c sbn  : snList) {
    		pcodes.add(sbn.Inventory__r.NCCode__c);
    	}
    	Map<String,List<Object>> pMap = getSalesMount(pcodes);

    	
    	List<SameBatchBean> sbTmp = new List<SameBatchBean>();
    	for (SameBatchNumber__c sbn  : snList) {
    		sbTmp.add(new SameBatchBean(sbn , pMap.get(sbn.Inventory__r.NCCode__c)));
    	}

    	resJson = EncodingUtil.urlEncode( JSON.serialize(sbTmp),'UTF-8');


    }

    public void Search(){
    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pserialNo = '';
    	pcategory0 = '';
    	pcategory1 = '';
    	 	//System.debug('***'+searchJson); 
    	//System.debug('***'+EncodingUtil.urlDecode(searchJson, 'UTF-8')); 
    	Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));
    	String type = String.valueOf(searchMap.get('type')) ;
    	String productName =  String.valueOf(searchMap.get('productName')) ;
		String brand =  String.valueOf(searchMap.get('brand')) ;
		String spec =  String.valueOf(searchMap.get('spec') );
		String cate0 =  String.valueOf(searchMap.get('cate0')) ;
		String nccode =  String.valueOf(searchMap.get('nccode')) ;
		String cate1=  String.valueOf(searchMap.get('cate1') );
		String serialNo=  String.valueOf(searchMap.get('serialNo') );


		if( productName != null && productName != '')pname = productName;
		if( brand != null && brand != '')pbrand = brand;
		if( spec != null && spec != '')pspec = spec;
		if( cate0 != null && cate0 != '')pcategory0 = cate0;
		if( cate1 != null && cate1 != '')pcategory1 = cate1;
		if( nccode != null && nccode != '')pnccode = nccode;
		if( serialNo != null && serialNo != '')pserialNo = serialNo;
		//if( ptype != null && ptype != '')productType = ptype;
		if(type == 'FromProduct'){//从产品中选择
			getProduct();
    	}else{//从历史中选择
			getOldProductList();

    	}


    }
    ///从产品中选择 //如果是第三方体系 则要排除系统中部中的产品
    public void getProduct(){

    	//System.debug('***'+ImportObject.getPicklistValues('Contract__c','Corpcode__c',false));

    	//String companycode = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(ap.Company__c);
    	//String sealflag  =  'Y-'+ companycode;

    	String sql = 'select Id,Name ,ProductName__c,brand__c,Spec__c ,SerialNo__c ,Model__c ,NCCode__c,Category1__c,Category2__c,Category0__c,zl__c,SealCompany__c ,TypeName__c';
    	 sql += ' from Product__c where  RecordType.DeveloperName = \'NCProduct\' and NCCode__c != null and Category0__c in (\'试剂\',\'耗品\',\'质控\',\'校准\') ';

        if(String.isBlank(pname) == false ) sql += ' and ProductName__c like \'%'+pname+'%\' ';
    	 if(String.isBlank(pbrand) == false ) sql += '  and Brand__c like \'%'+pbrand+'%\' ';
    	 if(String.isBlank(pspec) == false ) sql += '  and Spec__c like \'%'+pspec+'%\' ';
    	 if(String.isBlank(pnccode) == false ) sql += '  and NCCode__c like \'%'+pnccode+'%\' ';
    	 if(String.isBlank(pcategory0) == false ) sql += '  and Category0__c like \'%'+pcategory0+'%\' ';
    	 if(String.isBlank(pcategory1) == false ) sql += '  and Category1__c like \'%'+pcategory1+'%\' ';
    	 if(String.isBlank(pserialNo) == false ) sql += '  and SerialNo__c like \'%'+pserialNo+'%\' ';
    	 //if(String.isBlank(productType) == false ) sql += '  and TypeName__c like \'%'+productType+'%\' ';

    	 sql +=' limit 200 ';


    	List<Product__c>pList = Database.query(sql);
    	List<SameBatchBean> tmp = new List<SameBatchBean>();
    	if(pList == null || pList.size() == 0){
 	    	resJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
    	 	return;
    	 }
    	Set<String>  pids= new Set<String>();
    	for(Product__c p :pList){
    		//if(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)) continue;
    		pids.add(p.NCCode__c);
    	}
    	Map<String,List<Object>> pMap = getSalesMount(pids);

    	
    	List<SameBatchBean> sbTmp = new List<SameBatchBean>();
    	for (Product__c sbn  : pList) {
    		sbTmp.add(new SameBatchBean(sbn , pMap.get(sbn.NCCode__c)));
    	}
    	
    	resJson = EncodingUtil.urlEncode(JSON.serialize(sbTmp),'UTF-8');

    }

    public void setNil(){
    	searchJson = '';
    	resJson = '';
    	saveJson = '';
    	msg = '';
    }

    public Map<String,List<Object>>  getSalesMount(Set<String> ncs){

    	if(ncs == null || ncs.size() == 0)return null;
    	Map<String,List<Object>> resMap = new Map<String,List<Object>>();
    	String url = Label.queryResposityURL;
   
    	HttpRequest req = new HttpRequest();
     	String sql = '{"data":" '+ getSql(sc.Customer__r.AccountNumber ,sc.OwnerCompany__c , ncs )+'"}';

     	System.debug(sql);
      	req.setBody(sql);
      	req.setMethod('POST');
      	req.setHeader('Content-Type','text/plain');
      	req.setEndpoint(url);
        HttpResponse res  = null;
        try {
            res = Utils.postRequest(req, 2);
        }catch (Exception e) {
            return resMap;
        }
        
      ///返回结果处理
        if (res.getStatusCode() == 200) {
        	System.debug(res.getBody());
            Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"pk_corp\":\"1005\",\"vreceiptcode\":\"SO1811020001\",\"measname\":\"盒\",\"user_name\":\"四川大学华西医院\",\"ck_dvdate\":\"2019-08-25\",\"vdef4\":\"a160k000000lWF9AAM\",\"invcode\":\"110100100001\",\"fz_dvdate\":\"2019-08-25\",\"vdef3\":\"a150k000001B8l0AAC\",\"invname\":\"总蛋白测定试剂盒（双缩脲法）\",\"invpinpai\":\"迈克生物\",\"custname\":\"四川大学华西医院\",\"tatoldefnum\":10,\"psnname\":\"祝晓琳\",\"ck_vlot\":\"dxx1806252\",\"ck_num\":8,\"lastfreezenum\":0,\"invmnecode\":\"CH0101001\",\"vdef5\":\"SFBH\",\"totalfreezenum\":10,\"invtype\":\"TP:7170单\",\"fz_vlot\":\"dxx1806252\",\"invspec\":\"1\"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
        	if(r.get('code') == 0 || r.get('code') == '0'){
        		 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
	            if( rs.get('result') == 1 ){
	                List<Object> datas = (List<Object>)rs.get('data');
	               for(Object ob :datas){
	               		Map<String,Object> obm = (Map<String,Object>) ob ;
	               		String invcode = String.valueOf(obm.get('invcode'));
	               		List<Object> tmp = resMap.get(invcode) == null ? new List<Object>() : resMap.get(invcode);
	               		tmp.add(obm);
	               		resMap.put(invcode, tmp);
	                }
	               return resMap;
	           	}else{
	           		msg = String.valueOf(rs.get('result_msg'));
	           	}

      		//resJson = EncodingUtil.urlEncode(res.getBody(), 'UTF-8') ;
		    }else{
		    	msg = '查询历史销售数据失败 : '+String.valueOf(r.get('msg'));
		    	 ///System.debug(res.toString());
		    	//resJson = EncodingUtil.urlEncode('{"result":"","code":"1","msg":"接口错误,查询失败!"}','UTF-8');
		    }

	    }else{
	    	msg = '查询历史销售数据失败 : '+res.getBody();
	    }


    	return null;
    }
    public String getSql(String accNumber ,String comcode ,Set<String> ncs ){

    	String sql = '';
    	sql+='select * from ( ';
		sql+='select  ';
       	sql+='substr(z.dbilldate, 0, 7) salemonth, ';
       	sql+='c.invcode , ';
      	sql+='sum(b.nnumber) numb ';
  		sql+='from so_saleinvoice z ';
 		sql+='inner join so_saleinvoice_b b ';
    	sql+='on z.csaleid = b.csaleid ';
 		sql+='inner join bd_corp g ';
    	sql+='on z.pk_corp = g.pk_corp ';
 		sql+='inner join bd_cumandoc km ';
    	sql+='on z.creceiptcorpid = km.pk_cumandoc ';
 		sql+='inner join bd_cubasdoc k ';
    	sql+='on km.pk_cubasdoc = k.pk_cubasdoc ';
 		sql+='inner join bd_invbasdoc c ';
    	sql+='on b.cinvbasdocid = c.pk_invbasdoc ';
  		sql+='left join so_sale s ';
    	sql+='on b.csourcebillid = s.csaleid ';
 		sql+='where z.dr = 0 ';
   		sql+='and nvl(b.dr, 0) = \'0\' ';
   		sql+='and nvl(s.dr, 0) = \'0\' ';
   		sql+='and 	g.unitcode = \''+comcode+'\' ';
   		sql+='and k.custcode = \''+accNumber+'\' ';
   		sql+='and substr(z.dbilldate, 0, 7) >= ';
       	sql+='to_char(add_months(sysdate, -5), \'YYYY-MM\')   ';
 		sql+='group by  ';
        sql+='substr(z.dbilldate, 0, 7),	 ';
        sql+='c.invcode ';
        sql+=') p1 where p1.invcode in '+transStr(ncs);

    	return sql;

    }
    private String transStr (Set<String> nset){
    	if(nset == null || nset.size()== 0)return '()';
    	String s = JSON.serialize(nset);
    	s = s.replaceAll('"','\'');
		s = s.replace('[','(');
		s = s.replace(']',')');
		//System.debug(s);
		return s;

    }

    public class SameBatchBean {

    	public String name ;//产品名称
    	public String nccode ;//产品编码
    	public String spec ;//规格
    	public String brand ;//品牌
    	public String serial ;//货号
    	public String cate1;
    	public String cate2;
    	public String cate0;
    	public String opt;
    	public String prodid; //产品id 

    	public String invaliddate;
    	public String batchcode;
    	public String remark;

    	public String year {get;set;}
    	public Decimal  a1 {get;set;}
    	public Decimal a2 {get;set;}
		public Decimal a3 {get;set;}
    	public Decimal a4 {get;set;}
    	public Decimal a5 {get;set;}
    	public Decimal a6 {get;set;}
    	public Decimal a7 {get;set;}
    	public Decimal a8 {get;set;}
    	public Decimal a9 {get;set;}
    	public Decimal a10 {get;set;}
    	public Decimal a11 {get;set;}
    	public Decimal a12 {get;set;}

    	public String lm1sale {get;set;}//上月销量
    	public String lm2sale {get;set;}//上2月销量
    	public String  lm3sale {get;set;}//上3月销量

    	public SameBatchBean(SameBatchNumber__c sn , List<Object> lmsales ){

    		name = sn.Inventory__r.ProductName__c != null ? sn.Inventory__r.ProductName__c : sn.Inventory__r.Name;
    		nccode = sn.Inventory__r.NCCode__c;
    		spec = sn.Inventory__r.Spec__c;
    		brand = sn.Inventory__r.Brand__c;
    		serial = sn.Inventory__r.SerialNo__c;
    		prodid = sn.Inventory__c;

    		invaliddate = sn.ExpirationDate__c == null ? null : Utils.date2string(sn.ExpirationDate__c,'YYYY-MM-dd');
    		batchcode = sn.BatchNumber__c;
    		remark = sn.OtherRequirements__c ;

    		year = sn.SendYear__c;
    		a1 = sn.SendMount1__c;
    		a2 = sn.SendMount2__c;
    		a3 = sn.SendMount3__c;
    		a4 = sn.SendMount4__c;
    		a5 = sn.SendMount5__c;
    		a6 = sn.SendMount6__c;
    		a7 = sn.SendMount7__c;
    		a8 = sn.SendMount8__c;
    		a9 = sn.SendMount9__c;
    		a10 = sn.SendMount10__c;
    		a11 = sn.SendMount11__c;
    		a12 = sn.SendMount12__c;


    		if(lmsales == null)return;
    		for (Object o : lmsales  ) {
    			Map<String ,Object> l = (Map<String,Object>) o;
    			if(String.valueOf(l.get('salemonth'))== System.now().addMonths(-1).format('YYYY-MM') )lm1sale = String.valueOf(l.get('numb'));
    			if(String.valueOf(l.get('salemonth'))== System.now().addMonths(-2).format('YYYY-MM'))lm2sale = String.valueOf(l.get('numb'));
    			if(String.valueOf(l.get('salemonth'))== System.now().addMonths(-3).format('YYYY-MM'))lm3sale = String.valueOf(l.get('numb'));
    		}


    	}
    	public SameBatchBean(Product__c sn , List<Object> lmsales ){
    		name = sn.ProductName__c != null ? sn.ProductName__c : sn.Name;
    		nccode = sn.NCCode__c;
    		spec = sn.Spec__c;
    		brand = sn.Brand__c;
    		serial = sn.SerialNo__c;
    		cate1 = sn.Category1__c;
    		cate2 = sn.Category2__c;
    		cate0 = sn.Category0__c;
    		prodid = sn.Id;
    		year  = '';


    		if(lmsales == null)return;
    		for (Object o : lmsales  ) {
    			Map<String ,Object> l = (Map<String,Object>) o;
    			if(String.valueOf(l.get('salemonth'))== System.now().addMonths(-1).format('YYYY-MM') )lm1sale = String.valueOf(l.get('numb'));
    			if(String.valueOf(l.get('salemonth'))== System.now().addMonths(-2).format('YYYY-MM'))lm2sale = String.valueOf(l.get('numb'));
    			if(String.valueOf(l.get('salemonth'))== System.now().addMonths(-3).format('YYYY-MM'))lm3sale = String.valueOf(l.get('numb'));
    		}

    	}

    }
}